package com.hm.cms.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.hm.cms.auto.su.BaseDomain;
import com.hm.cms.domain.QTermsDomain;
import com.hm.cms.domain.TermsDomain;
import com.hm.cms.repository.TermsRepository;
import com.hm.cms.su.BeanUtil;
import com.hm.cms.vo.HcmsTermsVo;
import com.hm.common.exception.ErrorCode;
import com.hm.common.exception.ServiceException;
import com.hm.common.util.CommonUtil;

import lombok.extern.slf4j.Slf4j;

/**
 * @author shishun.wang
 * @date 下午2:05:06 2017年10月13日
 * @version 1.0
 * @describe 分类
 */
@Slf4j
@Service
public class TermsServiceImpl implements TermsService {

	@Autowired
	private TermsRepository termsRepository;

	@Override
	public String addTerms(HcmsTermsVo termsVo, String operationUserId) {
		if (CommonUtil.isAnyEmpty(termsVo.getTermCode(), termsVo.getTermName(), termsVo.getTermOrder())) {
			throw ServiceException.warning(ErrorCode.REQUIRED_PARAMETERS_MISSING);
		}

		QTermsDomain qTermsDomain = QTermsDomain.termsDomain;
		if (termsRepository.exists(
				qTermsDomain.termCode.eq(termsVo.getTermCode()).or(qTermsDomain.termName.eq(termsVo.getTermName())))) {
			throw ServiceException.warning(ErrorCode.DATA_EXISTING);
		}

		TermsDomain domain = new TermsDomain();
		{
			BeanUtil.copyProperties(termsVo, domain);
			BaseDomain.initBaseInfo(domain);
			domain.setCreateUser(operationUserId);
		}
		try {
//			StringUtil.trimOf(domain);
		}catch(Exception e) {
			log.error("去除对象字符串前后空格失败",e);
		}
		return termsRepository.save(domain).getId();
	}

	@Override
	public HcmsTermsVo getHcmsTermsByCode(String termCode){
		if (CommonUtil.isEmpty(termCode)) {
			throw ServiceException.warning(ErrorCode.REQUIRED_PARAMETERS_MISSING);
		}
		TermsDomain termsDomain = termsRepository.findOne(QTermsDomain.termsDomain.termCode.eq(termCode));
		if (CommonUtil.isEmpty(termsDomain)) {
			return null;
		}
		HcmsTermsVo vo = new HcmsTermsVo();
		BeanUtil.copyProperties(termsDomain, vo);
		return vo;
	}
	
	@Override
	public HcmsTermsVo getHcmsTermsByTermName(String termName){
		if (CommonUtil.isEmpty(termName)) {
			throw ServiceException.warning(ErrorCode.REQUIRED_PARAMETERS_MISSING);
		}
		TermsDomain termsDomain = termsRepository.findOne(QTermsDomain.termsDomain.termName.eq(termName));
		if (CommonUtil.isEmpty(termsDomain)) {
			return null;
		}
		HcmsTermsVo vo = new HcmsTermsVo();
		BeanUtil.copyProperties(termsDomain, vo);
		return vo;
	}
	
	@Override
	public HcmsTermsVo getHcmsTermsById(String termId){
		if (CommonUtil.isEmpty(termId)) {
			throw ServiceException.warning(ErrorCode.REQUIRED_PARAMETERS_MISSING);
		}
		TermsDomain termsDomain = termsRepository.findOne(termId);
		if (CommonUtil.isEmpty(termsDomain)) {
			return null;
		}
		HcmsTermsVo vo = new HcmsTermsVo();
		BeanUtil.copyProperties(termsDomain, vo);
		return vo;
	}
}
